package com.qjs.shiro.test.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.qjs.shiro.test.permission.MyPermission;

public class StaticRealm extends AuthorizingRealm{

	/**
	 * 权限检验：
	 * 第一步：加载权限信息
	 * 
	 * 用户授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("===AuthorizationInfo");
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		info.addRole("r1");
		info.addRole("r2");
		info.addObjectPermission(new MyPermission("+user+admin"));
		info.addStringPermission("+admin+*");
		info.addObjectPermission(new WildcardPermission("user：*"));
		return info;
	}
	
	/**
	 * 用户认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String name=(String) token.getPrincipal();
		String password=new String((char[])token.getCredentials());
		if(!"zs".equals(name)) throw new UnknownAccountException("用户名不存在");
		if(!"123".equals(password)) throw new IncorrectCredentialsException("密码错误");
		AuthenticationInfo info=new SimpleAuthenticationInfo("admin", password, getName());
		return info;
	}

}
